package com.zt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zt.enums.MembershipType;
import com.zt.enums.OrderStatus;
import com.zt.mapper.MembershipOrderMapper;
import com.zt.pojo.MembershipOrder;
import com.zt.pojo.request.MembershipOrderRequest;
import com.zt.service.MembershipService;
import com.zt.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class MembershipServiceImpl extends ServiceImpl<MembershipOrderMapper, MembershipOrder> implements MembershipService {
    private static final Logger log = LoggerFactory.getLogger(MembershipServiceImpl.class);
    
    @Autowired
    private UsersService usersService;

    @Override
    @Transactional
    public MembershipOrder createOrder(MembershipOrderRequest request) {
        // 参数校验
        if (request == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }
        if (request.getUserId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (request.getType() == null) {
            throw new IllegalArgumentException("会员类型不能为空");
        }
        if (request.getAmount() == null || request.getAmount() <= 0) {
            throw new IllegalArgumentException("订单金额必须大于0");
        }

        // 验证金额是否匹配
        double expectedAmount = request.getType().getPrice();
        if (Math.abs(request.getAmount() - expectedAmount) > 0.01) {
            throw new IllegalArgumentException("订单金额与会员类型不匹配");
        }

        MembershipOrder order = new MembershipOrder();
        order.setUserId(request.getUserId());
        order.setType(request.getType());
        order.setAmount(BigDecimal.valueOf(request.getAmount()));
        order.setStatus(OrderStatus.PENDING_PAYMENT);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        // 保存订单
        save(order);
        
        return order;
    }

    @Override
    public List<MembershipOrder> getUserOrders(Long userId) {
        return list(new LambdaQueryWrapper<MembershipOrder>()
                .eq(MembershipOrder::getUserId, userId)
                .orderByDesc(MembershipOrder::getCreateTime));
    }
    
    @Override
    @Transactional
    public boolean updateOrderPayStatus(String orderId) {
        // 查找订单
        MembershipOrder order = getById(orderId);
        if (order == null) {
            log.error("会员订单不存在, orderId={}", orderId);
            return false;
        }
        
        // 如果订单已经是已支付状态，无需再次更新
        if (OrderStatus.PAID.equals(order.getStatus())) {
            log.info("会员订单已经是已支付状态, orderId={}", orderId);
            return true;
        }
        
        // 更新订单状态为已支付
        LocalDateTime now = LocalDateTime.now();
        
        LambdaUpdateWrapper<MembershipOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MembershipOrder::getId, orderId)
                    .set(MembershipOrder::getStatus, OrderStatus.PAID)
                    .set(MembershipOrder::getPayTime, now)
                    .set(MembershipOrder::getUpdateTime, now);
        
        boolean updated = update(updateWrapper);
        
        if (updated) {
            // 获取会员类型对应的等级值
            Integer membershipLevel = getMembershipLevel(order.getType());
            
            // 获取会员类型的天数image.png
            int membershipDays = order.getType().getDays();
            
            // 更新用户会员状态
            if (membershipLevel != null) {
                boolean userUpdated = usersService.updateUserMembershipStatus(order.getUserId(), membershipLevel, membershipDays);
                if (!userUpdated) {
                    log.error("更新用户会员状态失败, userId={}, membershipLevel={}, days={}", order.getUserId(), membershipLevel, membershipDays);
                } else {
                    log.info("更新用户会员状态成功, userId={}, membershipLevel={}, days={}", order.getUserId(), membershipLevel, membershipDays);
                }
            }
        }
        
        return updated;
    }
    
    /**
     * 获取会员类型对应的等级值
     * @param type 会员类型
     * @return 会员等级值（1-普通会员，2-SVIP会员）
     */
    private Integer getMembershipLevel(MembershipType type) {
        if (type == null) {
            return null;
        }
        
        switch (type) {
            case MONTHLY:
            case QUARTERLY:
                return 2; // SVIP会员
            case ANNUAL:
                return 2; // SVIP会员
            default:
                return 1; // 普通会员
        }
    }
} 